package app.controllers.product;

import app.Const;
import app.models.app.ProductDetails;
import com.google.common.base.Strings;
import goja.GojaConfig;
import goja.StringPool;
import goja.mvc.Controller;
import goja.rapid.datatables.DTCriterias;
import goja.rapid.db.DaoKit;

/**
 * <p>
 * The url product/app Controller.
 * </p>
 *
 * @author sagyf yang
 * @version 1.0
 * @since JDK 1.6
 */
public class AppController extends Controller {

    public static final String FORM_ATTR = "pd";

    /**
     * The index route.
     * the url /product/app
     */
    public void index() {
        int product = getParaToInt();
        setAttr(Const.FIELD_PRODUCT, product);
    }


    public void dtlist() {
        final DTCriterias criterias = getCriterias();
        criterias.setParam(Const.FIELD_PRODUCT, getPara());
        renderDataTables(criterias, ProductDetails.class);
    }


    public void create() {
        setAttr(Const.ACTION_ATTR, Const.CREATE_ACTION);
        ProductDetails pd = new ProductDetails();
        pd.set(Const.FIELD_PRODUCT, getParaToInt());
        setAttr(FORM_ATTR, pd);
        render("item.ftl");
    }

    public void edit() {
        setAttr(Const.ACTION_ATTR, Const.EDIT_ACTION);
        ProductDetails pd = ProductDetails.dao.findById(getPara());
        setAttr(FORM_ATTR, pd);
        render("item.ftl");
    }

    public void save() {
        final ProductDetails pd = getModel(ProductDetails.class, FORM_ATTR);

        //PCWEB端展示
        if (!Strings.isNullOrEmpty(getPara("pd.pcweb_flag"))) {
            pd.set("pcweb_flag", Const.YES);
        } else {
            pd.set("pcweb_flag", Const.NO);
        }

        if (DaoKit.isNew(pd)) {
            pd.save();
            String url = GojaConfig.getProperty("api.domain", "http://127.0.0.1:8080/api/");
            pd.set("url", url + "product/intro/" + pd.getNumber(StringPool.PK_COLUMN).intValue());
            pd.update();
        } else {
            pd.update();
        }
        redirect("/product/app/" + pd.getNumber(Const.FIELD_PRODUCT).intValue());
    }


    public void delete() {
        if (ProductDetails.dao.deleteById(getPara())) {
            renderAjaxSuccess();
        } else {
            renderAjaxFailure();
        }
    }
}